<?php

namespace app\bsadmin\controller;

use think\facade\View;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;
use think\facade\Validate;
use think\exception\ValidateException;
use app\common\validate\User as UserValidate;
use app\common\model\User as UserModel;
use app\common\model\UserDisable as UserDisableModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserTimer as UserTimerModel;
use app\common\model\UserQq as UserQqModel;
use app\common\model\UserWx as UserWxModel;
use app\common\model\UserApple as UserAppleModel;
use app\common\model\UserScore as UserScoreModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\model\VipValueAdded as VipValueAddedModel;
use app\common\model\ApiLog as ApiLogModel;
use app\common\model\UserLoginLog as UserLoginLogModel;
use app\common\model\Company as CompanyModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\UserRealName as UserRealNameModel;
use app\common\model\UserRealNameLog as UserRealNameLogModel;
use app\common\model\Jobs as JobsModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\controller\Vip as VipController;
use app\common\model\Vip as VipModel;
use app\common\model\UserAvatarExamine as UserAvatarExamineModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;

class User extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'uid':
                        $where[] = ['user.id', '=', $G['key']];
                        break;
                    case 'user':
                        $where[] = ['user.user', '=', $G['key']];
                        break;
                    case 'mobile':
                        $where[] = ['user.mobile', '=', $G['key']];
                        break;
                    case 'email':
                        $where[] = ['user.email', '=', $G['key']];
                        break;
                }
            }
            if ($G['status'] != 'all') {
                $where[] = ['user.status', '=', $G['status']];
            }
            if ($G['role_type'] != 'all') {
                $where[] = ['user_info.role_type', '=', $G['role_type']];
            }
            $Data = UserModel::alias('user')->where($where)
                ->join('user_info user_info', 'user_info.uid = user.id', 'LEFT')
                ->join('company company', 'company.uid = user.id', 'LEFT')
                ->join('resume resume', 'resume.uid = user.id', 'LEFT')
                ->join('api_app app', 'app.app_id = user_info.app_id', 'LEFT')
                ->field('user.*,user_info.nickname,user_info.headimg,user_info.is_real_name,user_info.role_type,company.id as company_id,app.app_name,resume.id as resume_id')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '';
                    $v['headimg'] = $v['headimg'] ? config('web.imgurl') . $v['headimg'] : '';
                    $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                    $v['user_info'] = 0;
                    $v['data'] = [];
                    $v['log'] = UserDisableModel::alias('d')->where(['d.uid' => $v['id']])
                        ->join('admin admin', 'admin.id=d.admin_uid', 'LEFT')
                        ->field('d.status,d.disable_msg,d.auto_time,d.auto_status,d.create_time,admin.nickname')->order('d.id desc')->limit(10)
                        ->withAttr('auto_time', function ($v, $data) {
                            return $v ? date('Y-m-d H:i:s', $v) : '';
                        })->withAttr('nickname', function ($v, $data) {
                            return $v ? $v : '注销账号';
                        })->select();
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('index_mobile');
            return View::fetch();
        }
    }

    /**
     * 高级搜索
     * hhm
     * @return void
     */
    public function advancedSearch(){
        $S=input();
        $where = [];
        if (!empty($S['searchData'])){
            foreach  ($S['searchData'] as $v){
                switch ($v['value']){
                    case 'userStatus'://用户状态
                        //-1代表全部
                        if ($v['index']!=-1)
                            $where[]=['user.status','=',$v['index']];
                        break;
                    case 'userIdentity'://用户身份
                        if ($v['index']!=-1)
                            $where[]=['user_info.role_type','=',$v['index']];
                        break;
                    case 'RecentLogin'://最近登录时间
                        if ($v['index']!=-1)
                            $where[]=['timer.login_time','>=',getPastTimes($v['index'])];
                        break;
                    case 'RecentlyRegistered'://最近注册时间
                        if ($v['index']!=-1)
                            $where[]=['timer.register_time','>=',getPastTimes($v['index'])];
                        break;
                    case 'source'://数据来源
                        if ($v['index']!=-1)
                            $where[]=['app.app_id','=',$v['index']];
                        break;
                }
            }

        }
        $Data = UserModel::alias('user')->where($where)
            ->join('user_info user_info', 'user_info.uid = user.id', 'LEFT')
            ->join('company company', 'company.uid = user.id', 'LEFT')
            ->join('resume resume', 'resume.uid = user.id', 'LEFT')
            ->join('api_app app', 'app.app_id = user_info.app_id', 'LEFT')
            ->join('user_timer timer', 'timer.uid = user.id', 'LEFT')
            ->field('user.*,user_info.nickname,user_info.headimg,user_info.is_real_name,user_info.role_type,company.id as company_id,app.app_name,resume.id as resume_id')
            ->order('id desc')->paginate($S['pageSize'])->each(function ($v) {
                $v['nickname'] = $v['nickname'] ? base64_decode($v['nickname']) : '';
                $v['headimg'] = $v['headimg'] ? config('web.imgurl') . $v['headimg'] : '';
                $v['app_name'] = $v['app_name'] ? $v['app_name'] : '后台添加';
                $v['user_info'] = 0;
                $v['data'] = [];
                $v['log'] = UserDisableModel::alias('d')->where(['d.uid' => $v['id']])
                    ->join('admin admin', 'admin.id=d.admin_uid', 'LEFT')
                    ->field('d.status,d.disable_msg,d.auto_time,d.auto_status,d.create_time,admin.nickname')->order('d.id desc')->limit(10)
                    ->withAttr('auto_time', function ($v, $data) {
                        return $v ? date('Y-m-d H:i:s', $v) : '';
                    })->withAttr('nickname', function ($v, $data) {
                        return $v ? $v : '注销账号';
                    })->select();
                return $v;
            });
        if ($Data->items()) {
            return $this->ajaxReturn('', 0, $Data);
        } else {
            return $this->ajaxReturn('暂无数据~', -100);
        }
    }




    public function exemptLoginRedirect($uid)
    {
        $UserInfo = UserModel::getWebUserInfo(['user.id' => $uid]);
        $key = md5('Message:&' . request()->ip() . '&' . $UserInfo->id . '&' . time() . '&' . Str::random(8));
        $UserInfo->token = $key;
        $UserInfo->client_id = [];
        Session::set('User', $UserInfo->toArray());
        Cache::set('Message::' . $key, $UserInfo->id);
        $G = request()->get();
        return redirect(config('web.url') . '/user');
    }
    /**
     * 获取用户信息
     */
    public function getUserInfo($id)
    {
        $Find = UserModel::getUserInfoAll($id);
        if ($Find) {
            return $this->ajaxReturn('', 0, $Find);
        } else {
            return $this->ajaxReturn('无此用户数据', -100);
        }
    }
    public function addUser()
    {
        if (request()->isAjax()) {
            $D = request()->post();
            /**
             * 用户验证
             */
            try {
                validate(UserValidate::class)->scene('admin_add')->check($D);
            } catch (ValidateException $e) {
                return parent::ajaxReturn($e->getError(), -100);
            }
            $UserModel = new UserModel;
            $UserModel->user            =   $D['user'];
            $passHash = Str::random(4);
            $UserModel->password_hash       =   $passHash;
            $UserModel->password            =   UserModel::getPassword($passHash, $D['password']);
            if (!empty($D['mobile']))
                $UserModel->mobile = $D['mobile'];
            if (!empty($D['email'])) {
                $UserModel->email = $D['email'];
            } else {
                $UserModel->email = null;
            }
            $UserModel->status = $D['status'];
            if (!$D['status']) {
                $UserModel->disable_msg = $D['disable_msg'];
            } else {
                $UserModel->disable_msg = null;
            }
            $UserInfoModel = new UserInfoModel;
            $UserInfoModel->headimg         =   config('xy_default_avatar.user');
            if (!empty($D['headimg']))
                $UserInfoModel->headimg         =   $D['headimg'];
            $UserInfoModel->nickname        =   base64_encode($D['nickname']);
            $UserInfoModel->role_type         =   $D['role_type'];
            $UserTimerModel = new UserTimerModel;
            $UserTimerModel->online_time = time();
            $UserTimerModel->online_ip = request()->ip();
            $UserTimerModel->online_devices = substr(request()->header('user-agent'), 0, 200);
            $UserTimerModel->login_time = time();
            $UserTimerModel->login_ip = request()->ip();
            $UserTimerModel->login_devices = substr(request()->header('user-agent'), 0, 200);
            $UserTimerModel->register_time = time();
            $UserTimerModel->register_ip = request()->ip();
            $UserTimerModel->register_devices = substr(request()->header('user-agent'), 0, 200);
            // 启动事务
            Db::startTrans();
            try {
                $UserModel->save();
                $UserInfoModel->uid = $UserModel->id;
                $UserTimerModel->uid = $UserModel->id;
                $UserInfoModel->save();
                $UserTimerModel->save();
                // 提交事务
                Db::commit();
                return parent::ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return parent::ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('add_user_mobile');
            return View::fetch();
        }
    }
    public function editUser($id)
    {
        if (request()->isAjax()) {
            $D = request()->post();
            $UserModel = UserModel::where(['id' => $id])->find();
            if ($UserModel)
                $D['id'] = $UserModel->id;
            $D['uid'] = $UserModel->id;
            if (!empty($D['user']) && $UserModel->user == $D['user']) {
                $D['user'] = '';
            } else {
                $UserModel->user            =   $D['user'];
            }
            $scene = 'admin_add';
            if (!empty($D['transfer']))
                $scene = 'admin_edit';
            /**
             * 用户验证
             */
            try {
                validate(UserValidate::class)->scene($scene)->check($D);
            } catch (ValidateException $e) {
                return parent::ajaxReturn($e->getError(), -100);
            }
            if (!empty($D['transfer'])) {
                $TransferUserModel = UserModel::where(['mobile' => $D['mobile']])->find();
                if ($TransferUserModel) {
                    // 启动事务
                    Db::startTrans();
                    try {
                        $oldUser = [
                            'user' => $UserModel->user,
                            'mobile' => $UserModel->mobile,
                            'email' => $UserModel->email,
                            'password' => $UserModel->password,
                            'password_hash' => $UserModel->password_hash
                        ];
                        $UserModel->user = $TransferUserModel->user;
                        $UserModel->mobile = $TransferUserModel->mobile;
                        $UserModel->email = $TransferUserModel->email;
                        $UserModel->password = $TransferUserModel->password;
                        $UserModel->password_hash = $TransferUserModel->password_hash;

                        $TransferUserModel->user = null;
                        $TransferUserModel->mobile = null;
                        $TransferUserModel->email = null;
                        $TransferUserModel->save();

                        $oldUserWxModel = UserWxModel::where(['uid' => $UserModel->id])->find();
                        $oldUserQqModel = UserQqModel::where(['uid' => $UserModel->id])->find();
                        $oldUserAppleModel = UserAppleModel::where(['uid' => $UserModel->id])->find();
                        if ($oldUserWxModel) {
                            $oldUserWxModel->uid = null;
                            $oldUserWxModel->save();
                        }
                        if ($oldUserQqModel) {
                            $oldUserQqModel->uid = null;
                            $oldUserQqModel->save();
                        }
                        if ($oldUserAppleModel) {
                            $oldUserAppleModel->uid = null;
                            $oldUserAppleModel->save();
                        }
                        $UserWxModel = UserWxModel::where(['uid' => $TransferUserModel->id])->find();
                        $UserQqModel = UserQqModel::where(['uid' => $TransferUserModel->id])->find();
                        $UserAppleModel = UserAppleModel::where(['uid' => $TransferUserModel->id])->find();
                        if ($UserWxModel) {
                            $UserWxModel->uid = null;
                            $UserWxModel->save();
                        }
                        if ($UserQqModel) {
                            $UserQqModel->uid = null;
                            $UserQqModel->save();
                        }
                        if ($UserAppleModel) {
                            $UserAppleModel->uid = null;
                            $UserAppleModel->save();
                        }
                        // 提交事务
                        Db::commit();
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                    }

                    // 启动事务
                    Db::startTrans();
                    try {
                        $UserModel->save();
                        UserModel::where(['id' => $TransferUserModel->id])->update($oldUser);
                        // 提交事务
                        Db::commit();
                        return parent::ajaxReturn('已保存');
                    } catch (\Exception $e) {
                        // 回滚事务
                        Db::rollback();
                        return parent::ajaxReturn('保存失败，请重试', -100, ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                    }
                }
            }
            if (!empty($D['password'])) {
                if (UserModel::getPassword($UserModel->password_hash, $D['password']) == $UserModel->password)
                    return parent::ajaxReturn('新密码与旧密码相同', -100);
                $passHash = Str::random(4);
                $UserModel->password_hash       =   $passHash;
                $UserModel->password            =   UserModel::getPassword($passHash, $D['password']);
            }
            if (!empty($D['mobile']))
                $UserModel->mobile = $D['mobile'];
            if (!empty($D['email'])) {
                $UserModel->email = $D['email'];
            } else {
                $UserModel->email = null;
            }
            $UserModel->status = $D['status'];
            if (!$D['status']) {
                $UserModel->disable_msg = $D['disable_msg'];
            } else {
                $UserModel->disable_msg = null;
            }
            $UserQqModel = UserQqModel::where(['uid' => $UserModel->id])->field('id,uid')->find();
            if (!empty($D['unbind']) && in_array('unbindQq', $D['unbind']) && $UserQqModel) {
                $UserQqModel->uid = null;
            } else {
                $UserQqModel = null;
            }
            $UserWxModel = UserWxModel::where(['uid' => $UserModel->id])->field('id,uid')->find();
            if (!empty($D['unbind']) && in_array('unbindWx', $D['unbind']) && $UserWxModel) {
                $UserWxModel->uid = null;
            } else {
                $UserWxModel = null;
            }
            $UserAppleModel = UserAppleModel::where(['uid' => $UserModel->id])->field('id,uid')->find();
            if (!empty($D['unbind']) && in_array('unbindApple', $D['unbind']) && $UserAppleModel) {
                $UserAppleModel->uid = null;
            } else {
                $UserAppleModel = null;
            }
            $UserInfoModel = UserInfoModel::where(['uid' => $D['uid']])->find();
            if (!empty($D['headimg']))
                $UserInfoModel->headimg         =   $D['headimg'];
            if (!empty($D['nickname']))
                $UserInfoModel->nickname        =   base64_encode($D['nickname']);
            $UserInfoModel->role_type         =   $D['role_type'];
            $UserTimerModel = UserTimerModel::where(['uid' => $UserModel->id])->find();
            if (!$UserTimerModel) {
                $UserTimerModel = new UserTimerModel;
                $UserTimerModel->uid = $UserModel->id;
                $UserTimerModel->online_time = time();
                $UserTimerModel->online_ip = request()->ip();
                $UserTimerModel->online_devices = substr(request()->header('user-agent'), 0, 200);
                $UserTimerModel->login_time = time();
                $UserTimerModel->login_ip = request()->ip();
                $UserTimerModel->login_devices = substr(request()->header('user-agent'), 0, 200);
                $UserTimerModel->register_time = time();
                $UserTimerModel->register_ip = request()->ip();
                $UserTimerModel->register_devices = substr(request()->header('user-agent'), 0, 200);
            }
            // 启动事务
            Db::startTrans();
            try {
                $UserModel->save();
                $UserInfoModel->save();
                $UserTimerModel->save();
                if ($UserQqModel) $UserQqModel->save();
                if ($UserWxModel) $UserWxModel->save();
                if ($UserAppleModel) $UserAppleModel->save();
                // 提交事务
                Db::commit();
                return parent::ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return parent::ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $Find = UserModel::getUserInfoAll($id);
            View::assign('Find', $Find);
            if (request()->isMobile())
                return View::fetch('add_user_mobile');
            return View::fetch('add_user');
        }
    }
    public function setUserInfoRoleType($id, $status)
    {
        $UserInfoModel = UserInfoModel::where(['uid' => $id])->find();
        if ($UserInfoModel) {
            $UserInfoModel->role_type = $status;
            if ($UserInfoModel->save()) {
                return $this->ajaxReturn('已切换');
            } else {
                return parent::ajaxReturn('保存失败', -100);
            }
        } else {
            return parent::ajaxReturn('用户不存在', -100);
        }
    }
    public function setStatus($id)
    {
        if (request()->isPost()) {
            $D = request()->post();
            $UserModel = UserModel::where(['id' => $id])->find();
            $UserModel->status = 0;
            $UserModel->disable_msg = $D['msg'];
            $UserDisableModel = new UserDisableModel;
            $UserDisableModel->uid = $UserModel->id;
            $UserDisableModel->admin_uid = Session::get('AdminUser.uid');
            $UserDisableModel->disable_msg = $D['msg'];
            $UserDisableModel->status = 0;
            if ($D['auto_disable']) {
                $UserDisableModel->auto_time = strtotime($D['auto_disable'] . date(' H:i:s'));
                $UserDisableModel->auto_status = 0;
            }
            // 启动事务
            Db::startTrans();
            try {
                $UserModel->save();
                $UserDisableModel->save();
                // 提交事务
                Db::commit();
                return parent::ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return parent::ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $UserModel = UserModel::where(['id' => $id])->find();
            $UserModel->status = 1;
            $UserModel->disable_msg = '';
            $UserDisableModel = new UserDisableModel;
            $UserDisableModel->uid = $UserModel->id;
            $UserDisableModel->admin_uid = Session::get('AdminUser.uid');
            $UserDisableModel->status = 1;
            // 启动事务
            Db::startTrans();
            try {
                $UserModel->save();
                $UserDisableModel->save();
                if (UserDisableModel::where(['uid' => $UserModel->id, 'auto_status' => 0])->count())
                    UserDisableModel::where(['uid' => $UserModel->id, 'auto_status' => 0])->update(['auto_status' => 1]);
                // 提交事务
                Db::commit();
                return parent::ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return parent::ajaxReturn('保存失败，请重试', -100);
            }
        }
    }
    public function hasUser()
    {
        $D = request()->post();
        switch ($D['type']) {
            case 'mobile':
                $has = UserModel::where(['mobile' => $D['value']])->count();
                if ($has) {
                    return $this->ajaxReturn('用户已存在', 0, ['has' => $has]);
                } else {
                    return $this->ajaxReturn('用户不存在', 0, ['has' => $has]);
                }
                break;
            case 'email':
                $has = UserModel::where(['email' => $D['value']])->count();
                if ($has) {
                    return $this->ajaxReturn('用户已存在', 0, ['has' => $has]);
                } else {
                    return $this->ajaxReturn('用户不存在', 0, ['has' => $has]);
                }
                break;
        }
    }
    public function wxUser()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'uid':
                        $where[] = ['wx.uid', '=', $G['key']];
                        break;
                    case 'pc_openid':
                        $where[] = ['wx.pc_openid', '=', $G['key']];
                        break;
                    case 'wx_openid':
                        $where[] = ['wx.wx_openid', '=', $G['key']];
                        break;
                    case 'app_openid':
                        $where[] = ['wx.app_openid', '=', $G['key']];
                        break;
                    case 'mp_openid':
                        $where[] = ['wx.mp_openid', '=', $G['key']];
                        break;
                    case 'unionid':
                        $where[] = ['wx.unionid', '=', $G['key']];
                        break;
                }
            }
            if ($G['subscribe'] != 'all') {
                $where[] = ['wx.subscribe', '=', $G['subscribe']];
            }
            $Data = UserWxModel::alias('wx')->where($where)
                ->field('wx.*')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v->nickname = $v['nickname'] ? base64_decode($v['nickname']) : '';
                    $v->user_info = 0;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('wx_user_mobile');
            return View::fetch();
        }
    }
    public function qqUser()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'uid':
                        $where[] = ['qq.uid', '=', $G['key']];
                        break;
                    case 'pc_openid':
                        $where[] = ['qq.pc_openid', '=', $G['key']];
                        break;
                    case 'wx_openid':
                        $where[] = ['qq.wx_openid', '=', $G['key']];
                        break;
                    case 'app_openid':
                        $where[] = ['qq.app_openid', '=', $G['key']];
                        break;
                    case 'unionid':
                        $where[] = ['qq.unionid', '=', $G['key']];
                        break;
                }
            }
            if ($G['subscribe'] != 'all') {
                $where[] = ['user.subscribe', '=', $G['subscribe']];
            }
            $Data = UserQqModel::alias('qq')->where($where)
                ->field('qq.*')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v->nickname = $v['nickname'] ? base64_decode($v['nickname']) : '';
                    $v->user_info = 0;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('qq_user_mobile');
            return View::fetch();
        }
    }
    public function userApiLog()
    {
        if (request()->isAjax()) {
            $D = request()->get();
            list($where, $whereTime) = $this->getApiLogWhere();
            $ListObj = ApiLogModel::alias('l')->where($where);
            if (!empty($whereTime)) {
                $ListObj->whereTime('l.create_time', 'between', $whereTime);
            }
            $List = $ListObj->join('user_info user_info', 'user_info.uid = l.uid', 'LEFT')
                ->join('api_app app', 'app.app_id = l.app', 'LEFT')
                ->join('api_route api', 'api.api_id = l.api', 'LEFT')->field('l.*,user_info.nickname,user_info.headimg,app.app_name,api.api_name')
                ->order('l.id desc')->paginate($D['pageSize'])->each(function ($item, $key) {
                    $item->nickname = $item['nickname'] ? base64_decode($item['nickname']) : '';
                    $item->headimg = $item['headimg'] ? config('web.imgurl') . $item['headimg'] : '';
                });
            if ($List->items()) {
                return $this->ajaxReturn('success', 0, $List);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('user_api_log_mobile');
            return view();
        }
    }
    public function getApiLogWhere()
    {
        $D = request()->get();
        $where = [];
        if ($D['uid'] != '') {
            $where[] = ['l.uid', '=', $D['uid']];
        }
        if ($D['app_id'] != '') {
            $where[] = ['l.app', '=', $D['app_id']];
        }
        if ($D['api_id'] != '') {
            $where[] = ['l.api', '=', $D['api_id']];
        }
        if ($D['ip'] != '') {
            $where[] = ['l.ip', '=', $D['ip']];
        }
        $whereTime = [];
        if (!empty($D['time'])) {
            $whereTime[] = strtotime($D['time'][0] . ' 00:00:00');
            $whereTime[] = strtotime($D['time'][1] . ' 23:59:59');
        }
        return [$where, $whereTime];
    }
    public function exportApiLog()
    {
        if (request()->isAjax()) {
            $D = request()->get();
            list($where, $whereTime) = $this->getApiLogWhere();
            $ListObj = ApiLogModel::alias('l')->where($where);
            if (!empty($whereTime)) {
                $ListObj->whereTime('l.create_time', 'between', $whereTime);
            }
            $Data = $ListObj->join('user_info user_info', 'user_info.uid = l.uid', 'LEFT')
                ->join('api_app app', 'app.app_id = l.app', 'LEFT')
                ->join('api_route api', 'api.api_id = l.api', 'LEFT')->field('l.*,user_info.nickname,app.app_name,api.api_name')
                ->order('l.id desc')->paginate($D['pageSize'])->each(function ($item, $key) {
                    $item->nickname = $item['nickname'] ? base64_decode($item['nickname']) : '';
                });
            if ($Data->items()) {
                $title = [
                    ['title' => 'ID', 'key' => 'id'],
                    ['title' => 'UID', 'key' => 'uid'],
                    ['title' => '用户', 'key' => 'nickname'],
                    ['title' => '接口名称', 'key' => 'api_name'],
                    ['title' => '应用', 'key' => 'app_name'],
                    ['title' => '平台', 'key' => 'systype'],
                    ['title' => 'IP', 'key' => 'ip'],
                    ['title' => '参数', 'key' => 'param'],
                    ['title' => '访问时间', 'key' => 'create_time']
                ];
                $spreadsheet = new Spreadsheet;
                $sheet = $spreadsheet->getActiveSheet();

                //表头
                //设置单元格内容
                $titCol = 'A';
                foreach ($title as $key => $v) {
                    // 单元格内容写入
                    $sheet->setCellValue($titCol . '1', $v['title']);
                    $titCol++;
                }
                $row = 2;
                foreach ($Data->items() as $item) {
                    $dataCol = 'A';
                    foreach ($title as $key => $v) {
                        $sheet->setCellValue($dataCol . $row, $item[$v['key']]);
                        $dataCol++;
                    }
                    $row++;
                }
                $filename = 'output/log/api/' . Session::get('AdminUser.uid') . '_' . date('YmdHis') . Str::random(4) . '.xlsx';
                if (!file_exists(dirname($filename)))
                    mkdir(dirname($filename), 0777, true);
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filename);
                return $this->ajaxReturn('生成~', 0, ['url' => '/' . $filename]);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        }
    }
    public function userLoginLog()
    {
        if (request()->isAjax()) {
            $D = request()->get();
            list($where, $whereTime) = $this->getLoginLogWhere();
            $ListObj = UserLoginLogModel::alias('l')->where($where);
            if (!empty($whereTime)) {
                $ListObj->whereTime('l.create_time', 'between', $whereTime);
            }
            $List = $ListObj->join('user_info user_info', 'user_info.uid = l.uid', 'LEFT')
                ->join('api_app app', 'app.app_id = l.appid', 'LEFT')
                ->field('l.*,user_info.nickname,user_info.headimg,app.app_name')
                ->order('l.id desc')->paginate($D['pageSize'])->each(function ($item, $key) {
                    $item->nickname = $item['nickname'] ? base64_decode($item['nickname']) : '';
                    $item->headimg = $item['headimg'] ? config('web.imgurl') . $item['headimg'] : '';
                });
            if ($List->items()) {
                return $this->ajaxReturn('success', 0, $List);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('user_login_log_mobile');
            return view();
        }
    }
    public function getLoginLogWhere()
    {
        $D = request()->get();
        $where = [];
        if ($D['uid'] != '') {
            $where[] = ['l.uid', '=', $D['uid']];
        }
        if ($D['app_id'] != '') {
            $where[] = ['l.appid', '=', $D['app_id']];
        }
        if ($D['ip'] != '') {
            $where[] = ['l.ip', '=', $D['ip']];
        }
        $whereTime = [];
        if (!empty($D['time'])) {
            $whereTime[] = strtotime($D['time'][0] . ' 00:00:00');
            $whereTime[] = strtotime($D['time'][1] . ' 23:59:59');
        }
        return [$where, $whereTime];
    }
    public function exportLoginLog()
    {
        if (request()->isAjax()) {
            $D = request()->get();
            list($where, $whereTime) = $this->getLoginLogWhere();
            $ListObj = UserLoginLogModel::alias('l')->where($where);
            if (!empty($whereTime)) {
                $ListObj->whereTime('l.create_time', 'between', $whereTime);
            }
            $Data = $ListObj->join('user_info user_info', 'user_info.uid = l.uid', 'LEFT')
                ->join('api_app app', 'app.app_id = l.appid', 'LEFT')
                ->field('l.*,user_info.nickname,app.app_name')
                ->order('l.id desc')->paginate($D['pageSize'])->each(function ($item, $key) {
                    $item->nickname = $item['nickname'] ? base64_decode($item['nickname']) : '';
                });
            if ($Data->items()) {
                $title = [
                    ['title' => 'ID', 'key' => 'id'],
                    ['title' => 'UID', 'key' => 'uid'],
                    ['title' => '用户', 'key' => 'nickname'],
                    ['title' => '应用', 'key' => 'app_name'],
                    ['title' => '设备ID', 'key' => 'devices_id'],
                    ['title' => 'IP', 'key' => 'ip'],
                    ['title' => '登录时间', 'key' => 'create_time']
                ];
                $spreadsheet = new Spreadsheet;
                $sheet = $spreadsheet->getActiveSheet();

                //表头
                //设置单元格内容
                $titCol = 'A';
                foreach ($title as $key => $v) {
                    // 单元格内容写入
                    $sheet->setCellValue($titCol . '1', $v['title']);
                    $titCol++;
                }
                $row = 2;
                foreach ($Data->items() as $item) {
                    $dataCol = 'A';
                    foreach ($title as $key => $v) {
                        $sheet->setCellValue($dataCol . $row, $item[$v['key']]);
                        $dataCol++;
                    }
                    $row++;
                }
                $filename = 'output/log/api/' . Session::get('AdminUser.uid') . '_' . date('YmdHis') . Str::random(4) . '.xlsx';
                if (!file_exists(dirname($filename)))
                    mkdir(dirname($filename), 0777, true);
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filename);
                return $this->ajaxReturn('生成~', 0, ['url' => '/' . $filename]);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        }
    }
    public function score()
    {
        if (request()->isAjax()) {
            $D = request()->get();
            $where = [];
            if ($D['uid'] != '') {
                $where[] = ['score.uid', '=', $D['uid']];
            }
            $whereTime = [];
            if (!empty($D['time'])) {
                $whereTime[] = strtotime($D['time'][0] . ' 00:00:00');
                $whereTime[] = strtotime($D['time'][1] . ' 23:59:59');
            }
            $ListObj = UserScoreModel::alias('score')->where($where);
            if (!empty($whereTime)) {
                $ListObj->whereTime('score.create_time', 'between', $whereTime);
            }
            $List = $ListObj->join('user_info user_info', 'user_info.uid = score.uid', 'LEFT')
                ->field('score.*,user_info.nickname,user_info.headimg')
                ->order('score.id desc')->paginate($D['pageSize'])->each(function ($item, $key) {
                    $item->nickname = $item['nickname'] ? base64_decode($item['nickname']) : '';
                    $item->headimg = $item['headimg'] ? config('web.imgurl') . $item['headimg'] : '';
                });
            if ($List->items()) {
                return $this->ajaxReturn('success', 0, $List);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('score_mobile');
            return view();
        }
    }
    public function searchUser()
    {
        $G = request()->get();
        $DataModel = null;
        switch ($G['search_type']) {
            case 'uid':
                $DataModel = UserInfoModel::where('uid', 'like', '%' . $G['key'] . '%')->field('uid,nickname as value')->withAttr('value', function ($v) {
                    return base64_decode($v);
                })->limit(10)->select();
                break;
            case 'company_name':
                $DataModel = CompanyModel::where('title', 'like', '%' . $G['key'] . '%')->field('uid,title as value')->limit(10)->select();
                break;
            case 'resume_name':
                $DataModel = ResumeModel::where('name', 'like', '%' . $G['key'] . '%')->field('uid,name as value')->limit(10)->select();
                break;
            case 'mobile':
                $DataModel = UserModel::alias('user')->where('user.mobile', 'like', '%' . $G['key'] . '%')->join('user_info user_info', 'user_info.uid=user.id')->field('user.id as uid,user_info.nickname as value')->withAttr('value', function ($v) {
                    return base64_decode($v);
                })->limit(10)->select();
                break;
            case 'email':
                $DataModel = UserModel::alias('user')->where('user.email', 'like', '%' . $G['key'] . '%')->join('user_info user_info', 'user_info.uid=user.id')->field('user.id as uid,user_info.nickname as value')->withAttr('value', function ($v) {
                    return base64_decode($v);
                })->limit(10)->select();
                break;
        }
        if ($DataModel) {
            return $this->ajaxReturn('', 0, $DataModel);
        } else return $this->ajaxReturn();
    }
    public function RealName()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'uid':
                        $where[] = ['r.uid', '=', $G['key']];
                        break;
                    case 'id_number':
                        $where[] = ['r.id_number', '=', $G['key']];
                        break;
                    case 'name':
                        $where[] = ['r.name', 'like', '%' . $G['key'] . '%'];
                        break;
                }
            }
            if ($G['status'] != 'all')
                $where[] = ['r.status', '=', $G['status']];
            if (!empty($G['id_type']) && $G['id_type'] != 'all')
                $where[] = ['r.id_type', '=', $G['id_type']];
            $Data = UserRealNameModel::alias('r')->where($where)
                ->join('user_info user_info', 'user_info.uid = r.uid')
                ->join('area area1', 'area1.id = r.area1', 'LEFT')
                ->join('area area2', 'area2.id = r.area2', 'LEFT')
                ->join('area area3', 'area3.id = r.area3', 'LEFT')
                ->field('r.*,user_info.headimg,user_info.nickname,area1.title as area1,area2.title as area2,area3.title as area3')
                ->order('id desc')->paginate($G['pageSize'])->each(function ($v) {
                    $v->nickname = base64_decode($v['nickname']);
                    $v->img1 = $v['img1'] ? config('web.imgurl') . $v['img1'] : '';
                    $v->img2 = $v['img2'] ? config('web.imgurl') . $v['img2'] : '';
                    $v->img3 = $v['img3'] ? config('web.imgurl') . $v['img3'] : '';
                    $v->img4 = $v['img4'] ? config('web.imgurl') . $v['img4'] : '';
                    $v->img5 = $v['img5'] ? config('web.imgurl') . $v['img5'] : '';
                    $v->log = UserRealNameLogModel::alias('log')->where(['log.rid' => $v->id])->join('admin admin', 'admin.id = log.admin_uid', 'LEFT')
                        ->order('log.id desc')->field('log.*,admin.nickname')->limit(10)->select();
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('real_name_mobile');
            return View::fetch();
        }
    }
    public function setRealNameStatus()
    {
        $D = request()->post();
        $id = $D['id'];
        $status = $D['status'];
        $msg = $D['msg'];
        $UserRealNameModel = UserRealNameModel::where(['id' => $id])->find();
        if ($status == 1) {
            $UserRealNameModel->status = 1;
            $UserRealNameLogModel = new UserRealNameLogModel;
            $UserRealNameLogModel->rid = $UserRealNameModel->id;
            $UserRealNameLogModel->status = 1;
            $UserRealNameLogModel->msg = '审核通过';
            $UserRealNameLogModel->admin_uid = Session::get('AdminUser.uid');
            $UserRealNameLogModel->ip = request()->ip();
            $PushTaskModel = new PushTaskModel;
            $PushTaskModel->event       =   'RealNameNotice';
            $PushTaskModel->uid         =   $UserRealNameModel->uid;
            $PushData = $UserRealNameModel->toArray();
            $PushData['hi_text'] = '恭喜您';
            $PushData['status'] = '已通过';
            $PushData['msg'] = '通过';
            $PushData['time'] = date('Y-m-d H:i:s');
            $CompanyModel = null;
            $UserInfoModel = null;
            if ($UserRealNameModel->id_type) {
                $CompanyModel = CompanyModel::where(['uid' => $UserRealNameModel->uid])->find();
                $CompanyModel->attestation = 3;
                $CompanyModel->business_license = $UserRealNameModel->img3;
                if ($UserRealNameModel->id_number) {
                    $CompanyModel->uscc = $UserRealNameModel->id_number;
                    if (CompanyModel::where(['uscc' => $UserRealNameModel->id_number])->where('uid','<>',$UserRealNameModel->uid)->count())
                        return $this->ajaxReturn('此统一社会信用代码已实名', -100);
                }

                $PushData['id_type'] = '企业';
            } else {
                $UserInfoModel = UserInfoModel::where(['uid' => $UserRealNameModel->uid])->find();
                $UserInfoModel->name = $UserRealNameModel->name;
                $UserInfoModel->idcard = $UserRealNameModel->id_number;
                $UserInfoModel->is_real_name = 1;
                $PushData['id_type'] = '个人';
            }
            $PushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
            // 启动事务
            Db::startTrans();
            try {
                $UserRealNameModel->save();
                $PushTaskModel->save();
                $CompanyModel && $CompanyModel->save();
                $UserInfoModel && $UserInfoModel->save();
                $UserRealNameLogModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        } else {
            $UserRealNameModel->status = $status;
            $UserRealNameLogModel = new UserRealNameLogModel;
            $UserRealNameLogModel->rid = $UserRealNameModel->id;
            $UserRealNameLogModel->status = $status;
            $UserRealNameLogModel->msg = $msg;
            $UserRealNameLogModel->admin_uid = Session::get('AdminUser.uid');
            $UserRealNameLogModel->ip = request()->ip();
            $PushTaskModel = new PushTaskModel;
            $PushTaskModel->event       =   'RealNameNotice';
            $PushTaskModel->uid         =   $UserRealNameModel->uid;
            $PushData = $UserRealNameModel->toArray();
            $PushData['hi_text'] = '很遗憾';
            $PushData['status'] = '未通过';
            $PushData['msg'] = $msg;
            $PushData['time'] = date('Y-m-d H:i:s');
            $CompanyModel = null;
            $UserInfoModel = null;
            if ($UserRealNameModel->id_type) {
                $CompanyModel = CompanyModel::where(['uid' => $UserRealNameModel->uid])->find();
                $CompanyModel->attestation = 0;
                $CompanyModel->uscc = null;
                $CompanyModel->business_license = '';
                $PushData['id_type'] = '企业';
            } else {
                $UserInfoModel = UserInfoModel::where(['uid' => $UserRealNameModel->uid])->find();
                $UserInfoModel->name = '';
                $UserInfoModel->idcard = '';
                $UserInfoModel->is_real_name = 0;
                $PushData['id_type'] = '个人';
            }
            $PushTaskModel->data        =   json_encode($PushData, JSON_UNESCAPED_UNICODE);
            // 启动事务
            Db::startTrans();
            try {
                $UserRealNameModel->save();
                $UserRealNameLogModel->save();
                $PushTaskModel->save();
                $CompanyModel && $CompanyModel->save();
                $UserInfoModel && $UserInfoModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                p($e->getMessage());
                return $this->ajaxReturn('保存失败，请重试', -100);
            }
        }
    }
    public function getRights()
    {
        if (request()->isAjax()) {
            $G = request()->get();
            $where = [];
            if ($G['key']) {
                switch ($G['search_type']) {
                    case 'uid':
                        $where[] = ['rule.uid', '=', $G['key']];
                        break;
                    case 'user':
                        $where[] = ['user.user', '=', $G['key']];
                        break;
                    case 'mobile':
                        $where[] = ['user.mobile', '=', $G['key']];
                        break;
                    case 'email':
                        $where[] = ['user.email', '=', $G['key']];
                        break;
                }
            }
            if ($G['status'] != 'all')
                $where[] = ['rule.status', '=', $G['status']];
            $sort = 'rule.status desc,rule.expiry_time asc,rule.surplus_value desc,rule.level asc';
            if (!empty($G['sort'])) {
                switch ($G['sort']) {
                    case 'default':
                        $sort = 'rule.id desc';
                        break;
                }
            }
            $pageSize = 15;
            if (!empty($G['pageSize'])) {
                $pageSize = $G['pageSize'];
            }

            $Data = UserVipRuleModel::alias('rule')->where($where)
                ->join('user user', 'user.id=rule.uid')
                ->join('user_info user_info', 'user_info.uid=rule.uid')
                ->join('vip vip', 'vip.id=rule.vid', 'LEFT')
                ->join('company company', 'company.id=rule.uid', 'LEFT')
                ->join('user_vip user_vip', 'user_vip.uid=rule.uid', 'LEFT')
                ->join('vip_rule_value value', 'value.id=rule.rid', 'LEFT')
                ->field('user_info.nickname,user_info.headimg,rule.id,rule.uid,rule.value,rule.vid,rule.status,rule.surplus_value,rule.expiry_type,rule.is_company,rule.expiry_time,rule.create_time,vip.title as vip_name,rule.rid,value.title as rule_name,value.unit,value.alias,company.id as company_id,user_vip.company_vip_level,user_vip.company_vip_time,user_vip.personal_vip_time,user_vip.personal_vip_level')
                ->order($sort)->paginate($pageSize)->each(function ($v) {
                    if ($v->expiry_type || !$v->vid) {
                        $v->is_expiry = $v['expiry_time'] > time() ? 0 : 1;
                        $v->expiry_time = date('Y-m-d', $v['expiry_time']);
                    } else {
                        $expiry_time = $v->expiry_time;
                        if ($v->is_company) {
                            if ($v->company_vip_level)
                                $expiry_time = $v->company_vip_time;
                        } else {
                            if ($v->personal_vip_level)
                                $expiry_time = $v->personal_vip_time;
                        }
                        $v->is_expiry = $expiry_time > time() ? 0 : 1;
                        $v->expiry_time = date('Y-m-d', $expiry_time);
                    }
                    $v->nickname = base64_decode($v->nickname);
                    $v->headimg = config('web.imgurl') . $v->headimg;
                    if ($v->alias == 'release-jobs' && $v->company_id) {
                        $surplus_value = $v['surplus_value'] - JobsModel::where(['company_id' => $v->company_id])->whereNull('delete_time')->count();
                        $v->surplus_value = $surplus_value > 0 ? $surplus_value : 0;
                    }
                    if (!$v->vid) {
                        $value = VipValueAddedModel::alias('va')->where(['va.id' => $v->rid])
                            ->where(['type.alias' => 'vip/value_added_type'])
                            ->join('status_alias type', 'type.value=va.type')
                            ->field('va.title,type.type as unit')->find();
                        if ($value) {
                            $v->rule_name = $value->title;
                            $v->unit = $value->unit;
                        }
                    }
                });
            if ($Data->items()) {
                return $this->ajaxReturn('', 0, $Data);
            } else {
                return $this->ajaxReturn('暂无数据~', -100);
            }
        } else {
            if (request()->isMobile())
                return View::fetch('get_rights_mobile');
            return View::fetch();
        }
    }
    public function giveRights()
    {
        if (request()->isAjax()) {
            if (request()->isGet()) {
                $G = request()->get();
                $where = [];
                switch ($G['crowd']) {
                    case 'company':
                        $where[] = ['user_info.role_type', '=', 1];
                        break;
                    case 'personal':
                        $where[] = ['user_info.role_type', '=', 0];
                        break;
                    case 'mp':
                        $where[] = ['user_wx.subscribe', '=', 1];
                        break;
                    case 'mobile':
                        $where[] = ['user.mobile', 'NOT NULL', ''];
                        break;
                    case 'email':
                        $where[] = ['user.email', 'NOT NULL', ''];
                        break;
                }
                if ($G['vip_level'] != 'all') {
                    $where[] = ['user_vip.company_vip_level', '=', $G['vip_level']];
                }
                $whereTime = [];
                if (!empty($G['register_time'])) {
                    $whereTime[] = $G['register_time'][0] . ' 00:00:00';
                    $whereTime[] = $G['register_time'][1] . ' 23:59:59';
                }
                $DataObj = UserModel::alias('user')->where($where);
                if (!empty($whereTime))
                    $DataObj->whereTime('user.create_time', 'between', $whereTime);
                $Data = $DataObj->join('user_info user_info', 'user_info.uid = user.id', 'LEFT')
                    ->join('user_wx user_wx', 'user_wx.uid = user.id', 'LEFT')
                    ->join('user_vip user_vip', 'user_vip.uid = user.id', 'LEFT')
                    ->count();
                return $this->ajaxReturn('', 0, $Data);
            } else if (request()->isPost()) {
                $D = request()->post();
                $rule =   [
                    'vip_id'      => 'require',
                ];
                $msg  =   [
                    'vip_id.require' => '请选择套餐',
                ];
                $Validate = Validate::rule($rule)->message($msg);
                $result = $Validate->check($D);
                if (!$result) {
                    return $this->ajaxReturn($Validate->getError(), -100);
                }
                if (empty($D['vip_rule']))
                    return $this->ajaxReturn('当前无可赠送规则', -200);
                $ruleStatus = true;
                foreach ($D['vip_rule'] as $k => $v) {
                    if ($v['checked'] && $v['value']) {
                        $ruleStatus = false;
                    }
                }
                if ($ruleStatus)
                    return $this->ajaxReturn('当前无可赠送规则', -200);
                if ($D['crowd'] == 'appoint') {
                    $Data = $D['user_list'];
                } else {
                    $where = [];
                    switch ($D['crowd']) {
                        case 'company':
                            $where[] = ['user_info.role_type', '=', 1];
                            break;
                        case 'personal':
                            $where[] = ['user_info.role_type', '=', 0];
                            break;
                        case 'mp':
                            $where[] = ['user_wx.subscribe', '=', 1];
                            break;
                        case 'mobile':
                            $where[] = ['user.mobile', 'NOT NULL', ''];
                            break;
                        case 'email':
                            $where[] = ['user.email', 'NOT NULL', ''];
                            break;
                    }
                    if ($D['vip_level'] != 'all') {
                        $where[] = ['user_vip.company_vip_level', '=', $D['vip_level']];
                    }
                    $whereTime = [];
                    if (!empty($D['register_time'])) {
                        $whereTime[] = $D['register_time'][0] . ' 00:00:00';
                        $whereTime[] = $D['register_time'][1] . ' 23:59:59';
                    }
                    $DataObj = UserModel::alias('user')->where($where);
                    if (!empty($whereTime))
                        $DataObj->whereTime('user.create_time', 'between', $whereTime);
                    $Data = $DataObj->join('user_info user_info', 'user_info.uid = user.id', 'LEFT')
                        ->join('user_wx user_wx', 'user_wx.uid = user.id', 'LEFT')
                        ->join('user_vip user_vip', 'user_vip.uid = user.id', 'LEFT')
                        ->column('user.id');
                }
                if (count($Data) <= 0)
                    return $this->ajaxReturn('当前筛选结果为0', -200);
                $UserVipRuleList = [];
                $end_time = time() + 3600 * 24 * 30;
                $VipModel = VipModel::where(['id' => $D['vip_id']])->find();
                if ($VipModel->expiry_type) {
                    if (empty($D['end_time']))
                        return $this->ajaxReturn('有效期不能为空', -200);
                    $end_time = strtotime($D['end_time']);
                }
                $UserScoreList = [];
                $UserScoreUpdateList = [];
                foreach ($Data as $key => $uid) {
                    foreach ($D['vip_rule'] as $k => $v) {
                        if ($v['checked'] && $v['value']) {
                            if ($v['alias'] == 'bonus-points') {
                                $ScoreUpdateFind = [
                                    'uid' => $uid,
                                    'score' => Db::raw('score+' . $v['value'])
                                ];
                                ksort($ScoreUpdateFind);
                                $UserScoreUpdateList[] = $ScoreUpdateFind;
                                $ScoreFind = [
                                    'uid' => $uid,
                                    'tid' => 0,
                                    'score' => $v['value'],
                                    'desc' => '赠送' . $v['value'] . '积分'
                                ];
                                ksort($ScoreFind);
                                $UserScoreList[] = $ScoreFind;
                            } else {
                                $RuleFind = [
                                    'vid'       =>  $v['vid'],
                                    'rid'       =>  $v['rid'],
                                    'value'     =>  $v['value'],
                                    'alias'     =>  $v['alias'],
                                    'uid'       =>  $uid,
                                    'level'     =>  $VipModel->level,
                                    'surplus_value'  =>  $v['value'],
                                    'expiry_time' =>  $end_time,
                                ];
                                $RuleFind['expiry_type'] = $VipModel->expiry_type;
                                $RuleFind['is_company'] = $VipModel->is_company;
                                ksort($RuleFind);
                                $UserVipRuleList[] = $RuleFind;
                            }
                        }
                    }
                }
                $UserVipRuleModel = new UserVipRuleModel;
                $UserVipModel = new UserVipModel;
                $UserInfoModel = new UserInfoModel;
                $UserScoreModel = new UserScoreModel;
                // 启动事务
                Db::startTrans();
                try {
                    if (!empty($UserVipRuleList)) $UserVipRuleModel->saveAll($UserVipRuleList);
                    $UserVipModel->whereIn('uid', $Data)->update(['update_vip' => 1]);
                    if (!empty($UserScoreUpdateList)) {
                        foreach ($UserScoreUpdateList as $k => $v) {
                            $UserInfoModel->where(['uid' => $v['uid']])->update($v);
                        }
                    }
                    if (!empty($UserScoreList)) $UserScoreModel->saveAll($UserScoreList);
                    // 提交事务
                    Db::commit();
                    return $this->ajaxReturn('赠送成功');
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->ajaxReturn('赠送失败，请重试', -200, ['msg' => $e->getMessage(), 'line' => $e->getLine()]);
                }
            }
        } else {
            $G = request()->get();
            if (!empty($G['uid'])) {
                $userList = UserInfoModel::where('uid', 'in', explode(',', $G['uid']))->field('uid,nickname as value')->withAttr('value', function ($v) {
                    return base64_decode($v);
                })->limit(10)->select();
                View::assign('user_list', $userList);
            }
            $VipController = VipController::getCate();
            View::assign('vip', $VipController);
            $Vip = VipController::getSelect([], true);
            View::assign('VipList', $Vip);
            if (request()->isMobile())
                return View::fetch('give_rights_mobile');
            return View::fetch();
        }
    }
    public function editRights($id)
    {
        if (request()->isPost()) {
            $D = request()->post();
            $UserVipRuleModel = UserVipRuleModel::where(['id' => $id])->find();
            $UserVipRuleModel->value = intval($D['surplus_value']);
            $UserVipRuleModel->surplus_value = intval($D['surplus_value']);
            if (intval($D['surplus_value']) <= 0) {
                $UserVipRuleModel->surplus_value = 0;
                $UserVipRuleModel->status = 0;
            }
            $UserVipRuleModel->expiry_time = strtotime($D['expiry_time'] . ' 00:00:00');
            $UserVipModel = UserVipModel::where(['uid' => $UserVipRuleModel->uid])->find();
            $UserVipModel->update_vip = 1;
            // 启动事务
            Db::startTrans();
            try {
                $UserVipRuleModel->save();
                $UserVipModel->save();
                // 提交事务
                Db::commit();
                $updateData = [
                    'value'         =>  $UserVipRuleModel->value,
                    'surplus_value' =>  $UserVipRuleModel->surplus_value,
                    'status'        =>  $UserVipRuleModel->status,
                    'expiry_time'   =>  date('Y-m-d', $UserVipRuleModel->expiry_time),
                    'is_expiry'     =>  $UserVipRuleModel->expiry_time > time() ? 0 : 1,
                ];
                return $this->ajaxReturn('已更改', 0, $updateData);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试', -200);
            }
        }
    }
    public function invalidRights($id)
    {
        $UserVipRuleModel = UserVipRuleModel::where(['id' => $id])->find();
        $UserVipRuleModel->expiry_time = time() - 1;
        $UserVipRuleModel->status = 0;
        $UserVipModel = UserVipModel::where(['uid' => $UserVipRuleModel->uid])->find();
        $UserVipModel->update_vip = 1;
        // 启动事务
        Db::startTrans();
        try {
            $UserVipRuleModel->save();
            $UserVipModel->save();
            // 提交事务
            Db::commit();
            return $this->ajaxReturn();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('保存失败，请重试', -200);
        }
    }

    public function avatar()
    {
        if (!request()->isAjax()) {
            if (request()->isMobile())
                return View::fetch('avatar_mobile');
            return View::fetch();
        }
        $page = input('page', 1);
        $limit = input('pageSize', 10);
        $type = input('search_type', null);
        $key = input('key', null);
        $status = (!empty(input('status')) || is_numeric(input('status'))) ? input('status') : [0, 1, 2];
        $where = [];
        if ($type == 'mobile') {
            // 若key不为空，则按照传入的key筛选手机号符合的数据，反之查询所有
            $where[] = empty($key) ? true : ['user.mobile', 'LIKE', $key . '%'];
        } else {
            // 若key不为空，则按照传入的key筛选企业id符合的数据，反之查询所有
            $where[] = empty($key) ? true : ['info.id' => $key];
        }
        $where[] = ['examine.status', 'IN', $status];
        $data = UserAvatarExamineModel::alias('examine')
            ->join('user user', 'user.id=examine.uid')
            ->join('user_info info', 'info.uid=examine.uid')
            ->where($where)
            ->field([
                'examine.*',
                'info.nickname' => 'nickname',
                'user.mobile' => 'mobile'
            ])
            ->page($page, $limit)
            ->select();
        $total = UserAvatarExamineModel::alias('examine')
            ->join('user user', 'user.id=examine.uid')
            ->join('user_info info', 'info.uid=examine.uid')
            ->where($where)
            ->count();
        $result = [
            'data' => $data,
            'total' => $total
        ];
        return $this->ajaxReturn('success', 0, $result);
    }

    public function setAvatarStatus($id, $status)
    {
        $reason = input('post.reason', '');
        $avatar = UserAvatarExamineModel::where('id', $id)->find();
        if (!$avatar) {
            return $this->ajaxReturn('错误的参数！', -100);
        }
        // 审核通过
        if ($status == 1) {
            $avatar->status = 1;
            UserInfoModel::where('uid', $avatar->uid)->update(['headimg' => $avatar->after_avatar]);
            $avatar->reason = $reason;
            $avatar->save();
        } else {
            $avatar->status = 2;
            $avatar->reason = $reason;
            $avatar->save();
        }
        $msg = $status == 1 ? '已通过' : '已驳回';
        return $this->ajaxReturn($msg, 0);
    }
}
